<?php 
$GLOBALS['Md'] = "TimeClock";
$GLOBALS['Pd'] = "B";
require_once($_SERVER['DOCUMENT_ROOT']."/defaultconf.mex");
echo heade(); 
echo body(); 
module($BSD['DB00']);
office_header($_SESSION[$SESSOF]);
include($GLOBALS['PAD']."Modules/TimeClock/main.obj.php");
include($GLOBALS['PAD']."Modules/TimeClock/nav.views.php");
echo NavBack();

	$sysTime = date("Y-m-d H:i:s");
	$TToTime = '';
	$TAvTime = '';
		
	$Mon = 'mon'.date("w");
	
	$Sevr = split(" ",$sysTime);
	$Sev = split(":",$Sevr[1]);
	$Sev = ($Sev[0]-4).':'.$Sev[1].':'.$Sev[2];
	$Sev = $Sevr[0].' '.$Sev;
	
	function timecalc($timestart,$timeend) {
		$UnixvStart = strtotime($timestart);
		$UnixvEnd = strtotime($timeend);
		$UnixCalc = $UnixvEnd-$UnixvStart;
		$Cal = date("H:i:s",$UnixCalc-3600);
		return $Cal;
	}

	// Verif Faltas
	$QProfiles = "SELECT 
		timeclock_profiles.ref,
		timeclock_profiles.main_users_ref AS USER,
		timeclock_profiles.delay,
		timeclock_profiles.{$Mon},
		timeclock_profiles.ProfileType AS Type,
		timeclock_ttables.entrytime,
		timeclock_ttables.ref AS Tabs
			FROM timeclock_profiles
		INNER JOIN timeclock_ttables ON timeclock_ttables.ref = timeclock_profiles.{$Mon}
		WHERE TIME(timeclock_ttables.entrytime) < TIME('{$Sev}')
		AND '{$sysTime}' BETWEEN timeclock_profiles.TimeIni AND timeclock_profiles.TimeEnd";
	$Profiles = $GLOBALS['CONN']->db_array($QProfiles); 
	for ($r = 1; $r <= $Profiles[0]; $r++) { 
	
		$QOp = "SELECT ref FROM timeclock_operations WHERE 
							main_users_ref = {$Profiles[$r]['USER']}
							AND DATE(time_main) = DATE('{$sysTime}')";
							$Op = $GLOBALS['CONN']->db_array($QOp); 
							
		if (!isset($Op[1]) && $Profiles[$r]['Type'] == 1) {
		
		$CVacs = "SELECT ref FROM timeclock_vacs
							WHERE RefUser = {$Profiles[$r]['USER']}
							 AND Status = 4
							 AND TimeStart < '{$sysTime}' AND
							 TimeEnd > '{$sysTime}'";
							$Jvac = $GLOBALS['CONN']->db_query($CVacs); 
							
		if (!isset($Jvac[1])) {
							
		$QOp = "INSERT INTO timeclock_operations 
							(main_users_ref, time_main, RefTTable)
							 VALUES 
							 ({$Profiles[$r]['USER']},'{$sysTime}',{$Profiles[$r]['Tabs']})";
							$GLOBALS['CONN']->db_query($QOp); 

		$QOp = "SELECT ref FROM timeclock_operations WHERE 
							main_users_ref = {$Profiles[$r]['USER']}
							AND DATE(time_main) = DATE('{$sysTime}')";
							$Op = $GLOBALS['CONN']->db_array($QOp); 
							
		$QO = "INSERT INTO timeclock_delays 
				(main_user_ref, delaylevel, delaytime, EventTime, Status, RefType, RefOperation) 
				VALUES 
				({$Profiles[$r]['USER']}, 0, 0, '{$sysTime}', 1, 2, {$Op[1]['ref']})";
				$GLOBALS['CONN']->db_query($QO);
				}
		}
	
	}
	
	if (!isset($_GET['Month'])) {$_GET['Month'] = date("m");}
	if (!isset($_GET['Year'])) {$_GET['Year'] = date("Y");}
	$Mon = 'mon'.date("w");
?> 
<table width="100%"  border="0" cellpadding="10">
  <tr>
    <td>
	Hoje
	  <table width="100%"  border="0" cellpadding="3" cellspacing="1">
      <form action="index.php" method="get" name="getData">
	<?php if (isset($_GET['Submit'])) {?>
    <tr bgcolor="#ACB1CC">
		<td align="right" colspan="13">
		<a href="<?php echo $GLOBALS['URL'];?>Modules/TimeClock/Templates/daily.php?Group=<?php echo $_GET['Group'];?>&Time=<?php echo $_GET['Time'];?>&Offices=<?php echo $_GET['Offices'];?>" target="_blank"><img src="<?php echo $GLOBALS['GFX'];?>Objects/print.png" alt="Imprimir" border="0"></a></td>
    </tr>
	<?PHP } ?>
        <tr bgcolor="#99CCCC">
          <td bgcolor="#ACB1CC" colspan="13">Dia:
        <input name="Time" type="text" onFocus="this.select();lcs(this)" 
	  onClick="event.cancelBubble=true;this.select();lcs(this)" 
	  value="<?php if (!isset($_GET['Time'])) { $_GET['Time'] = date("Ymd");}
	  echo $_GET['Time'];  ?>" size="14">
        e 
        <input name="Time2" type="text" onFocus="this.select();lcs(this)" 
	  onClick="event.cancelBubble=true;this.select();lcs(this)" 
	  value="<?php if (!isset($_GET['Time2'])) { $_GET['Time2'] = date("Ymd");}
	  echo $_GET['Time2']; ?>" size="14">
        <select name="Offices">
   	<?php
	echo '<option value="">Todos</option>';

	$QCallOffice = "SELECT * FROM main_offices WHERE Type IN (1,2,5) = '1' ORDER BY name ASC";
	$CallOffice = $GLOBALS['CONN']->db_array($QCallOffice); 
	for ($o = 1; $o <= $CallOffice[0]; $o++) {

       echo '<option value="'.$CallOffice[$o]['ref'].'"';
		if (isset($_GET['Offices']) && $_GET['Offices'] == $CallOffice[$o]['ref']) { 
		echo "selected";}
		echo '>'.$CallOffice[$o]['name'].'</option>';
         } ?>
        </select> 
        <select name="Users" id="Users">
          <?php
	echo '<option value="">Todos</option>';

	$CUser = "SELECT main_users.ref, main_users.name FROM main_users
						INNER JOIN timeclock_profiles AS b ON b.main_users_ref = main_users.ref 
						ORDER BY name ASC";
	$User = $GLOBALS['CONN']->db_array($CUser); 
	for ($o = 1; $o <= $User[0]; $o++) {

       echo '<option value="'.$User[$o]['ref'].'"';
		if (isset($_GET['Users']) && $_GET['Users'] == $User[$o]['ref']) { 
		echo "selected";}
		echo '>'.$User[$o]['name'].'</option>';
         } ?>
                </select>
        <input type="submit" name="Submit" value="Ver"></td>
        </tr>
      </form>
        <tr bgcolor="#F2F2F2">
          <td width="18%" rowspan="2"><div align="center">Funcionário</div></td>
          <td width="18%" rowspan="2"><div align="center">Departamento</div></td>
          <td width="10%" rowspan="2"><div align="center">Data </div></td>
          <td width="9%" rowspan="2"><div align="center">Início </div></td>
          <td width="9%" rowspan="2"><div align="center">Fim</div></td>
          <td colspan="2"><div align="center">Estatísticas</div></td>
          <td colspan="2"><div align="center">Dia</div></td>
          <td colspan="2"><div align="center">AlmoÇo</div></td>
          <td colspan="2"><div align="center">Outros</div></td>
        </tr>
        <tr bgcolor="#F2F2F2">
          <td width="9%"><div align="center">&Uacute;til</div></td>
          <td width="9%"><div align="center">DiferenÇa</div></td>
          <td width="9%"><div align="center">Entrada </div></td>
          <td width="9%"><div align="center">Saída </div></td>
          <td width="9%"><div align="center">Início</div></td>
          <td width="9%"><div align="center">Fim</div></td>
		  <td width="9%"><div align="center">Atrasos</div></td>
		  <td width="9%"><div align="center">Comp.</div></td>
        </tr>
   <?php
 if (isset($_GET['Offices']) && $_GET['Offices'] != "") { 
			$Offices = " AND m.ref = {$_GET['Offices']}";
			} else {
			$Offices = "";
			}
 if (isset($_GET['Users']) && $_GET['Users'] != "") { 
			$Users = " AND n.ref = {$_GET['Users']}";
			} else {
			$Users = "";
			}
   $QProfiles = "SELECT 
						DATE(g.time_main) AS DAt,
						TIME(g.InTime) AS InTime,
						TIME(g.OutTime) AS OutTime,
						TIME(g.LunchStart) AS LunchStart,
						TIME(g.LunchEnd) AS LunchEnd,
						TIME(b.leavetime) AS leavetime,
						TIME(b.entrytime) AS entrytime,
						TIME(b.lunchend) AS lunchend,
						TIME(b.lunchstart) AS lunchstart,
						g.ref AS Op,
						m.name AS office,
						n.name AS name,
						a.ref,
						a.main_users_ref,
						a.delay,
						a.ProfileType,
						CONCAT(HOUR(b.entrytime),':',MINUTE(b.entrytime)) AS SchedEntry,
						CONCAT(HOUR(b.leavetime),':',MINUTE(b.leavetime)) AS SchedOut
				FROM  timeclock_operations AS g 
		LEFT OUTER JOIN timeclock_profiles AS a ON g.main_users_ref = a.main_users_ref AND g.time_main BETWEEN a.TimeIni AND a.TimeEnd
		INNER JOIN timeclock_ttables AS b ON b.ref = g.RefTTable
		INNER JOIN main_users AS n ON n.ref = a.main_users_ref
		INNER JOIN main_offices AS m ON n.ref_office = m.ref
		WHERE DATE(g.time_main) BETWEEN '{$_GET['Time']}' AND '{$_GET['Time2']}'
		{$Offices}
		{$Users}
		ORDER BY g.time_main, m.name ASC, n.name ASC";
	$Profiles = $GLOBALS['CONN']->db_array($QProfiles); 
	for ($f = 1; $f <= $Profiles[0]; $f++) { 
	
		$line1 = '<tr bgcolor="#D3D6E4">';
		$line2 = '<td>'.$Profiles[$f]['name'].'</td>
		<td>'.$Profiles[$f]['office'].'</td>';
	   
	    $CVacs = "SELECT a.TimeEnd, l.name FROM timeclock_vacs AS a
		INNER JOIN htck_types AS l ON l.Ref = a.Type
		WHERE '{$Profiles[$f]['DAt']}' BETWEEN TimeStart AND TimeEnd 
		AND a.RefUser = {$Profiles[$f]['main_users_ref']}
		AND Status > 3 AND Status != 5";
		$Vacs = $GLOBALS['CONN']->db_array($CVacs);
		
	if (isset($Vacs[1])) {
	
		echo $line1.$line2.'<td colspan="11">'.$Vacs[1]['name'].' at� '.$Vacs[1]['TimeEnd'].'</td>';
		
	} elseif ($Profiles[$f]['ProfileType'] == 2) {
	
		echo $line1.$line2.'<td colspan="11">Isento</td>';
	
	} elseif (isset($Profiles[$f]['InTime']) != '') { 
 
		echo $line1.$line2.'<td NOWRAP>'.$Profiles[$f]['DAt'].'</td>
		<td NOWRAP>'.$Profiles[$f]['SchedEntry'].'</td>
		<td NOWRAP>'.$Profiles[$f]['SchedOut'].'</td>
		<td>';
	if ($Profiles[$f]['OutTime'] == null) {
	$Eve = 112;
	$Profiles[$f]['OutTime'] = $Profiles[$f]['leavetime'];
	} if ($Profiles[$f]['OutTime'] < $Profiles[$f]['InTime']) {
	$AvTime = '0';
	} else {
	$AvTime = (strtotime($Profiles[$f]['OutTime'])-strtotime($Profiles[$f]['InTime']))-((strtotime($Profiles[$f]['LunchEnd'])-strtotime($Profiles[$f]['LunchStart'])));
	} echo date("H:i:s",$AvTime-3600);
	$TAvTime = $TAvTime+$AvTime;
	echo '</td>
		<td>';
	$ScTime = (strtotime($Profiles[$f]['leavetime'])-strtotime($Profiles[$f]['entrytime']))-((strtotime($Profiles[$f]['lunchend'])-strtotime($Profiles[$f]['lunchstart'])));
	$ToTime = $AvTime-$ScTime;
	$TToTime = $TToTime+$ToTime;
	if ($ToTime < 0) {
		echo '<font color="#FF0000">'.date("H:i:s",0-$ToTime-3600).'</font>';
	} else {
		echo date("H:i:s",$ToTime-3600);
	}
	echo '</td>
		<td>'.$Profiles[$f]['InTime'].'</td>
		<td>'.$Profiles[$f]['OutTime'].'</td>
		<td>'.$Profiles[$f]['LunchStart'].'</td>
		<td>'.$Profiles[$f]['LunchEnd'].'</td>
		<td>';

	$QEvent = "SELECT * FROM timeclock_delays
	WHERE refOperation = {$Profiles[$f]['Op']}";
	$Event = $GLOBALS['CONN']->db_array($QEvent);
	if (isset($Event[1])) { 
			echo date("H:i:s", $Event[1]['delaytime']-3600);
			}
		echo '</td><td>';
		
	$QEvent = "SELECT * FROM timeclock_xtime
	WHERE refOperation = {$Profiles[$f]['Op']}";
	$Event = $GLOBALS['CONN']->db_array($QEvent);
	if (isset($Event[1])) { 
			echo date("H:i:s", $Event[1]['EventTime']);
			}
		echo '</td>';
	
	} else { 
         
		 $line1 = '<tr bgcolor="#F2F2F2">';
		 
		echo $line1.$line2.'<td>'.$Profiles[$f]['DAt'].'</td><td>'.$Profiles[$f]['SchedEntry'].'</td>
		<td colspan="10">NÃo compareceu </td>';
   } 
   		echo '</tr>';

 }  ?>
    </table>
	<br>
	<?php /*
	Mês
	<table width="100%"  border="0" cellpadding="3" cellspacing="1">
      <form action="?" method="post" name="getData" runat="server">
        <tr bgcolor="#99CCCC">
          <td bgcolor="#ACB1CC" colspan="10">Mês:
            <select name="Month" id="Month">
              <option value="01">Jan</option>
              <option value="02">Fev</option>
              <option value="03">Dez</option>
            </select> 
            <select name="Year" id="Year">
              <option>2007</option>
              <option>2008</option>
              </select>
            <input type="submit" name="Submit" value="Ver"></td>
        </tr>
      </form>
        <tr bgcolor="#F2F2F2">
          <td width="18%">Funcionário</td>
          <td width="15%">Departamento</td>
		  <td width="11%">%</td>
		  <td width="12%">BalanÇo</td>
          <td width="12%">Atrasos</td>
          <td width="12%">Faltas</td>
          <td width="12%">Sa�das</td>
          <td width="12%">CompensaÇ&otilde;es</td>
          <td width="12%">Média Diária </td>
		  <td width="12%">Média AlmoÇo</td>
	    </tr>
   <?php
    $QProfiles = "SELECT 
						g.name AS office, 
						f.name,
						 COUNT(e.ref) AS Num2,
						 COUNT(c.ref) AS Ev1,
						 COUNT(c.ref) AS Ev2,
						 COUNT(c.ref) AS Ev3,
						 COUNT(d.ref) AS Ev4,
						 (COUNT(d.ref)-(COUNT(c.ref)+COUNT(c.ref)+COUNT(c.ref))) AS Bal,
						 COUNT(a.ref) AS Num,
						 AVG(TIME(a.InTime)) AS SchedEntry,
						 AVG(TIME(a.OutTime)) AS SchedOut,
						 AVG(TIME(a.LunchStart)) AS SchedLStart,
						 AVG(TIME(a.LunchEnd)) AS SchedLEnd
				FROM timeclock_operations AS a
		INNER JOIN timeclock_profiles AS b ON b.main_users_ref = a.main_users_ref
		LEFT OUTER JOIN timeclock_delays AS c ON c.refOperation = a.ref
		LEFT OUTER JOIN timeclock_xtime AS d ON d.refOperation = a.ref
		INNER JOIN timeclock_ttables AS e ON e.ref = a.RefTTable
		INNER JOIN main_users AS f ON f.ref = a.main_users_ref
		INNER JOIN main_offices AS g ON f.ref_office = g.ref
		WHERE YEAR(a.time_main) = {$_GET['Year']} AND MONTH(a.time_main) = {$_GET['Month']}
		GROUP BY a.main_users_ref
		ORDER BY office ASC, name ASC";
	$Profiles = $GLOBALS['CONN']->db_array($QProfiles); 
	for ($f = 1; $f <= $Profiles[0]; $f++) { 
  echo '<tr bgcolor="#D3D6E4">
		<td>'.$Profiles[$f]['name'].'</td>
		<td>'.$Profiles[$f]['office'].'</td>
		<td>'.$Profiles[$f]['SchedLEnd'].'%</td>
		<td>'.$Profiles[$f]['Bal'].'</td>
		<td>'.$Profiles[$f]['Ev1'].'</td>
		<td>'.$Profiles[$f]['Ev2'].'</td>
		<td>'.$Profiles[$f]['Ev3'].'</td>
		<td>'.$Profiles[$f]['Ev4'].'</td>
		<td>';
		echo date("H:i:s",($Profiles[$f]['SchedLStart']));
		$AvgLunch = timecalc($Profiles[$f]['SchedLStart'],$Profiles[$f]['SchedLEnd']);
		$AvgSched = timecalc($Profiles[$f]['SchedEntry'],$Profiles[$f]['SchedOut']);
		echo timecalc($AvgSched,$AvgLunch).'</td>
		<td>';
		echo date("H:i:s",$Profiles[$f]['SchedEntry']-3600);
		echo '</td>
		</tr>';
   } ?>
  </table>*/ ?>
	</tr>
</table>
<?php echo footer();?>